package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@SpringBootApplication(scanBasePackages = {"com.example.demo"})
@EnableWebMvc
@EntityScan(basePackages = {"com.example.demo.domain"})
@EnableTransactionManagement
public class SimpleDynamicDatasourceApplication implements TransactionManagementConfigurer {

    public static void main(String[] args) {
        SpringApplication.run(SimpleDynamicDatasourceApplication.class, args);
    }

    @Bean
    public HibernateTransactionManager txManager() {
        HibernateTransactionManager txm = new HibernateTransactionManager(sessionFactory().getObject());
        return txm;
    }

    @Bean(name = {"sessionFactory"})
    public HibernateJpaSessionFactoryBean sessionFactory() {
        return new HibernateJpaSessionFactoryBean();
    }

    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return txManager();
    }
}
